<template>
  <el-dialog
    top="50px"
    class="preview-config-wrapper"
    :destroy-on-close="true"
    :show-close="false"
    :title="title"
    draggable
    @closed="closedDialog"
    v-model="dialogVisible"
    :width="`${previewTab == 1 ? '498' : '785'}`"
  >
    <div class="preview-panel-wrapper" v-loading="loading" element-loading-text="加载中...">
      <PreviewPanel :isMobile="isMobile" />
      <div style="display: flex; justify-content: center; margin-top: 10px;" v-if="showDel">
        <div style="padding: 5px 20px;border: 1px solid #0081fa; color: #0081fa; cursor: pointer;border-radius: 8px;" @click="delUserResult">删除该记录</div>
      </div>
    </div>
  </el-dialog>
</template>
<script setup>
import { ref } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import PreviewPanel from './PreviewPanel.vue'
import { noLoginGet as getPublishedSurveyInfo } from '@/management/api/dataform'
import { initRuleEngine } from '@/render/hooks/useRuleEngine.js'
import { get as _get } from 'lodash-es'
import { isMobile } from '@/render/utils/index'

const emit = defineEmits(['delete'])
const store = useStore()
const route = useRoute()

const dialogVisible = ref(false);
const openDialog = (val) => {
  console.log('openDialog', val);
  
  formId.value = val.formId || route.params.id || ''
  userId.value = val.userId || ''
  batchCode.value = val.batchCode || ''
  showDel.value = val.showDel || false
  store.commit('preview/setSurveyPath', formId.value)
  store.commit('preview/setBatchCode', val.batchCode || '')
  getDetail()
  dialogVisible.value = true;
};

const previewTab = ref(1)
previewTab.value = isMobile() ? 1 : 2
const formId = ref('')
const userId = ref('')
const batchCode = ref('')
const showDel = ref(false)
const title = ref('查看详情')
const loading = ref(true)

const getDetail = async () => {
  try {
    const res = await getPublishedSurveyInfo(formId.value)
    loadData(res)
    // }
  } catch (error) {
    console.log(error)

    loading.value = false
  }
}
const loadData = async (res) => {
  if (res?.result?.formId) {
    const { dataFormAttributeList } = res.result
    const schema = res.result.skinConf ? JSON.parse(res.result.skinConf) : {}

    const bannerConf = _get(schema, 'bannerConf', {
      "titleConfig": {
        "mainTitle": res.result.formRemark || "",
        "subTitle": res.result.formName || ""
      },
      "bannerConfig": {
        "bgImage": "",
        "videoLink": "",
        "postImg": ""
      }
    })
    const bottomConf = _get(schema, 'bottomConf', {
      "logoImage": "",
      "logoImageWidth": "60%"
    })
    const baseConf = _get(schema, 'baseConf', {
      "begTime": res.result.startTime,
      "endTime": res.result.endTime,
      "tLimit": 0,
      "answerLimitTime": 0,
      "isMultiple": true,
      "anonymous": true,
      "isUpdate": true,
      "isDel": true,
      "isTop": true,
      "language": "chinese",
      "answerBegTime": "00:00:00",
      "answerEndTime": "23:59:59",
      "answerUser": [],
      "adminUser": []
    })
    const skinConf = _get(schema, 'skinConf', {
      "skinColor": "#4a4c5b",
      "inputBgColor": "#ffffff",
      "backgroundConf": {
        "color": "#fff"
      },
      "themeConf": {
        "color": "#0081fa"
      },
      "contentConf": {
        "opacity": 100
      }
    })
    const submitConf = _get(schema, 'submitConf', {
      "submitTitle": "提交",
      "confirmAgain": {
        "is_again": false,
        "again_text": "确认要提交吗？"
      },
      "msgContent": {
        "msg_200": "提交成功",
        "msg_9001": "您来晚了，感谢支持问卷~",
        "msg_9002": "请勿多次提交！",
        "msg_9003": "您来晚了，已经满额！",
        "msg_9004": "提交失败！"
      }
    })
    const logicConf = _get(schema, 'logicConf', {
      "showLogicConf": []
    }) 
    const dataConf = _get(schema, 'dataConf', {
        "dataList": []
      })

    const metaData = {
      ...res.result,
      skinConf: '',
      "_id": res.result.formId,
      "createDate": res.result.createTime,
      "updateDate": res.result.lastModifyTime,
      "title": res.result.formName || '调研活动',
      "remark": res.result.formRemark,
      "surveyType": res.result.formType,
      "surveyPath": res.result.formId,
      "creatorName": res.result.creatorName || 'admin',
      "owner": res.result.creatorName || 'admin',
      "ownerId": res.result.creatorId,
      "createMethod": "basic",
      "currentUserId": res.result.creatorId,
      "isCollaborated": false
    }

    let dataList = []
    console.log('dataConf', dataConf)
    dataFormAttributeList.forEach((item) => {
      let fields = item.attrContent ? JSON.parse(item.attrContent) : {}
      dataList.push({
        ...item,
        ...fields,
        field: item.attrId
      })
    })

    let cf = {
      dataList: dataList
    }
    console.log('cf', cf)
    const questionData = {
      metaData,
      bannerConf,
      baseConf,
      bottomConf,
      dataConf: cf,
      skinConf,
      submitConf
    }

    // document.title = res.result.formName 
    title.value = '查看详情 - ' + res.result.formName

    console.log('questionData', questionData)
    // store.commit('setSurveyPath', surveyPath)
    store.dispatch('preview/init', questionData)
    initRuleEngine(logicConf?.showLogicConf)

    setTimeout(() => {
      loading.value = false
    }, 1000)
  } else {
    setTimeout(() => {
      loading.value = false
    }, 1000)
    throw new Error(res?.serverResult?.resultMessage || '活动不存在')
  }
}
// const updateForm = (item, dataList) => {
//   console.log('item', item)
//   console.log('dataConf.value', dataList)
//   let myResultList = item.myDataFormResultList
//   dataList.forEach((item) => {
//     item.value = item.value || ''
//     let idx = myResultList.findIndex((itm) => itm.attrId === item.attrId)
//     if (idx > -1) {
//       const data = {
//         key: item.attrId,
//         value: myResultList[idx].dataFormResult
//       }
//       store.commit('preview/changeFormData', data)
//     }
//   })
// }
const delUserResult = async () => {
  if (!showDel.value) {
    return
  }
  try {
    await ElMessageBox.confirm('是否确认删除？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
  } catch (error) {
    return
  }
  const res = await deleteById({
    id: batchCode.value,
    formId: formId.value,
    userId: userId.value
  })
  if (res?.serverResult?.resultCode !== '200') {
    ElMessage.error(res?.serverResult?.resultMessage)
    return
  }
  emit('delete')
  ElMessage.success('删除成功')
  closedDialog()
}
const closedDialog = () => {
  loading.value = false
  dialogVisible.value = false
}

defineExpose({ openDialog });
</script>
<style lang="scss" scoped>
@use '@/management/styles/edit-btn.scss' as *;

.preview-panel {
  :deep(.preview-config-wrapper) {
    background-color: transparent;
    box-shadow: none;
    padding: 0;
  }
  .ml75 {
    margin-left: 75px;
  }

  .view-icon {
    font-size: 20px;
    height: 29px;
    line-height: 29px;
  }

  .preview-tab {
    display: flex;
    align-items: center;
    justify-content: center;

    .border-right-none {
      border-right: none;
    }

    .active {
      border-color: $primary-color;
      color: $primary-color;
    }

    .border-left-none {
      border-left: none;
    }

    &-item {
      width: 80px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #ffffff;
      border: 1px solid rgba(227, 228, 232, 1);
      cursor: pointer;
      &:hover {
        border-color: $primary-color;
        color: $primary-color;
      }
    }
  }
  .preview-panel {
    margin-top: 16px;
    .preview-panel-wrapper {
      height: 100%;
      overflow: hidden;
      border-radius: 0 0 60px 60px;
    }
    &.pc {
      display: flex;
      justify-content: center;
      background: #f1f2f3;
      box-shadow: 0px 2px 10px -2px rgba(82, 82, 102, 0.2);
      height: 726px;
      .wrapper {
        width: 636px;
        height: 704px;
      }
      .preview-panel-wrapper {
        border-radius: 0;
      }
    }
    &.phone {
      display: flex;
      align-items: center;
      justify-content: center;

      .wrapper {
        background: url('@assets/images/preview-phone.png') no-repeat;
        width: 442px;
        height: 810px;
        background-size: 100% 100%;
        padding: 0 26px;
        padding-top: 72px;
        padding-bottom: 22px;
        display: flex;
        flex-direction: column;
      }
      iframe {
        border-radius: 0px 0px 50px 50px;
      }
    }
  }
  .tips-wrapper {
    display: flex;
    align-items: center;
    background: $primary-bg-color;
    color: $primary-color;
    font-size: 12px;
    padding: 2px 0;
    padding-left: 9px;

    span {
      margin-left: 5px;
    }
  }
}
.btn.preview-btn {
  // .btn-txt {
  //   font-size: 14px;
  // }
  // flex-direction: row;
  align-items: center;
  &:hover {
    color: $primary-color;
  }
  // margin-right: 10px;
}
</style>
